#!/usr/bin/env python3
# coding=utf-8

import numpy as np
import pandas as pd
import random as rd
import copy as cp
import plotly.express as px
import plotly.graph_objects as go

x = np.array(range(-50, 51, 1))
x2 = np.array(range(-2, 3, 1))
y = np.zeros(len(x), dtype=float)
y_noised = np.zeros(len(x), dtype=float)
kernel = np.zeros(len(x2), dtype=float)

# 原始序列
k = 0
for i in x:
    y[k] = i * i
    k = k + 1

# 原始序列加噪
for i in range(0, len(y)):
    y_noised[i] = y[i] + rd.uniform(-300, 300)

# 生成核
k = 0
for i in x2:
    kernel[k] = -i * i * i * i + 1000
    k = k + 1
# 直接指定核
kernel = np.array([1.0, 1.0, 1.0, 1.0, 1.0])
# kernel = np.array([1.0, 5.0, 10.0, 5.0, 1.0])
# 归一化后的核
nkernel = kernel / sum(kernel)
print(nkernel)

# 一维卷积
z1 = np.convolve(y_noised, kernel, mode='same')
z2 = np.convolve(y_noised, nkernel, mode='same')

df = pd.DataFrame(data={
    'x': x,
    'src': y,
    'noised': y_noised,
    'z1': z1,
    'z2': z2
})

part = df[8:len(df) - 8]

# fig = px.line(part, x='x', y=['src', 'noised', 'z'], title='曲线一维卷积',labels={'x':'t', 'y':'cos(t)'})

fig = go.Figure()
# Add traces
fig.add_trace(go.Scatter(x=part['x'], y=part['src'],
                         line=dict(color='rgba(0,0,255,0.25)', width=16),
                         mode='lines',
                         name='原始'))
fig.add_trace(go.Scatter(x=part['x'], y=part['noised'],
                         line=dict(color='rgba(0,0,0,0.4)', width=5),
                         mode='lines',
                         name='加噪后'))

fig.add_trace(go.Scatter(x=part['x'], y=part['z1'],
                         line=dict(color='rgba(0,255,36,1)',
                                   width=3, dash='dash'),
                         mode='lines',
                         name='卷积'))

fig.add_trace(go.Scatter(x=part['x'], y=part['z2'],
                         line=dict(color='rgba(255,20,0,1)', width=7),
                         mode='lines',
                         name='归一化后卷积'))
# Edit the layout
fig.update_layout(title='曲线一维卷积，卷积核[1,1,1,1,1]',
                  xaxis_title='x',
                  yaxis_title='取值')

fig.update_layout(title={
    'y': 0.87,
    'font': {
        'size': 38,
    }
})

fig.update_layout(legend={
    'orientation': 'h',
    'yanchor': "top",  # y轴顶部
    'y': 0.99,
    'xanchor': "right",
    'x': 0.99,
    'font': {
        'size': 30,
    },
    'title': {
        'text': '',
        'font': {
            'size': 30,
            }
    }
})

fig.show()						# 展示图表
